/**
 * Created by cchen on 2015/5/19.
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match;
        });
    };
}


'use strict';
angular.module('backofficeApp.CSOpsManager.controller', []).
    controller('topListCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.communityList = []

        $scope.currentTab = ''

        $scope.numPages = 999;
        $scope.numPerPageList = [10, 25, 50, 100, 250, 500]

        var defaultNumPerPage = 50


        /** =================== Users Tab =================== */

        $scope.topUsers = []

        $scope.communityU = 'all'
        //$scope.currentPageU = 1;
        $scope.numPerPageU = defaultNumPerPage;
        $scope.filterU = 'daysActive'

        $scope.filterListU = {
            daysActive: 'daysActive',
            questions: '发布数',
            replies: '回复数',
            activities: '活动发布数',
            contribution: '贡献'
        }

        $scope.getTopUsersData = function (comm) {
            $scope.communityU = comm == null ? 'all' : comm
            $scope.orderByFieldU = $scope.filterU
            $scope.reverseSortU = true

            $('#loadingTextU').html('Loading...')

            $scope.topUsers = []
            getTopUsersAPI()
        }
        //
        //$scope.onSelectPageU = function (page) {
        //    $scope.currentPageU = page;
        //    $scope.getTopUsersData($scope.communityU);
        //};

        function getTopUsersAPI() {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/BI/reports/getTopUsers/' + $scope.communityU + '/' + $scope.numPerPageU + '/' + $scope.filterU, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var len = data.data.length
                for (var i = 0; i < len; i++) {
                    var U = data.data[i]
                    //U['rank'] = i + 1 + $scope.numPerPageU * ($scope.currentPageU - 1)
                    U['rank'] = i + 1
                    $scope.topUsers.push(U)
                }
                $('#loadingTextU').html('')
            }).error(function () {
            });
        }

        // Sort columns
        $scope.orderByFieldU = 'daysActive';
        $scope.reverseSortU = true;

        var pageLoadedU = false
        $scope.initPageUsers = function () {
            $scope.currentTab = 'Users'
            if (!pageLoadedU) {
                getTopUsersAPI()
                pageLoadedU = true
            }
        }

        /** =================== Questions Tab =================== */

        $scope.topQuestions = []

        $scope.communityQ = 'all'
        $scope.numPerPageQ = defaultNumPerPage;
        $scope.filterQ = 'browserCount'

        $scope.filterListQ = {browserCount: '浏览量', replyCount: '回复数'}

        $scope.getTopQuestionsData = function (comm) {
            $scope.communityQ = comm == null ? 'all' : comm
            $scope.orderByFieldQ = $scope.filterQ
            $scope.reverseSortQ = true

            $('#loadingTextQ').html('Loading...')

            $scope.topQuestions = []
            getTopQuestionsAPI()
        }

        function getTopQuestionsAPI() {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/BI/reports/getTopQuestions/' + $scope.communityQ + '/' + $scope.numPerPageQ + '/' + $scope.filterQ, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var len = data.data.length
                for (var i = 0; i < len; i++) {
                    var Q = data.data[i]
                    Q['categoryName'] = questionCategory[Q['category']]
                    Q['rank'] = i + 1
                    $scope.topQuestions.push(Q)
                }
                $('#loadingTextQ').html('')
            }).error(function () {
            });
        }

        var questionCategory = {
            question: '邻里求助',
            share: '推荐分享',
            activity: '邻里活动',
            secondhand: '二手闲置',
            free: '免费赠送',
            lostAndFound: '失物招领',
            advertisement: '邻里杂谈'
        };

        // Sort columns
        $scope.orderByFieldQ = 'browserCount';
        $scope.reverseSortQ = true;

        var pageLoadedQ = false
        $scope.initPageQuestions = function () {
            $scope.currentTab = 'Questions'
            if (!pageLoadedQ) {
                getTopQuestionsAPI()
                pageLoadedQ = true
            }
        }


        /** =================== Activities Tab =================== */

        $scope.topActivities = []

        $scope.communityA = 'all'
        $scope.numPerPageA = defaultNumPerPage;
        $scope.filterA = 'partakeNum'

        $scope.filterListA = {partakeNum: '参加人数', browserCount: '浏览量', replyCount: '回复数'}


        $scope.getTopActivitiesData = function (comm) {
            $scope.communityA = comm == null ? 'all' : comm
            $scope.orderByFieldA = $scope.filterA
            $scope.reverseSortA = true

            $('#loadingTextA').html('Loading...')

            $scope.topActivities = []
            getTopActivitiesAPI()
        }

        function getTopActivitiesAPI() {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/BI/reports/getTopActivities/' + $scope.communityA + '/' + $scope.numPerPageA + '/' + $scope.filterA, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var len = data.data.length
                for (var i = 0; i < len; i++) {
                    var A = data.data[i]
                    A['rank'] = i + 1
                    $scope.topActivities.push(A)
                }
                $('#loadingTextA').html('')
            }).error(function () {
            });
        }

        // Sort columns
        $scope.orderByFieldA = 'partakeNum';
        $scope.reverseSortA = true;

        var pageLoadedA = false
        $scope.initPageActivities = function () {
            $scope.currentTab = 'Activities'
            if (!pageLoadedA) {
                getTopActivitiesAPI()
                pageLoadedA = true
            }
        }


        /** =================== =================== */

        function initPage() {
            function getCommListAPI() {
                $http.get('http://' + backOfficeHost + '/rest/v1.0/communities/getAllCommunityFromSQL', {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    var len = data.data.length
                    for (var i = 0; i < len; i++) {
                        if (data.data[i].isValid == 'True')
                            $scope.communityList.push(data.data[i])
                    }
                }).error(function () {
                });
            }

            getCommListAPI()
            $scope.initPageUsers()
        }

        initPage()

        $scope.exportData = function () {
            var table = $scope.currentTab[0]
            var blob = new Blob([document.getElementById('exportable' + table).innerHTML], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
            });
            saveAs(blob, "top{0}{1}.xls".format($scope['numPerPage' + table], $scope.currentTab));
        }

    }])